<?php
class Common {
	
	public static function makepass($maxlen){
		$passchar=array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		$p="";
		for($i=0;$i<$maxlen;$i++){
			$p .= $passchar[rand(0,35)];
		}
		return $p;
	}
	
	public static function makeID($now,$maxlen){
		$now++;
		$nowlen=strlen((string)$now);
		$p="";
		for($i=$maxlen;$i>$nowlen;$i--){
			$p.="0";
		}
		(string)$p .= (string)$now;
		return $p;
	}


    /**
     * @param $emailAdd string|array email address
     * @param $subject string subject
     * @param $content string content email
     * @return bool
     */
    public static function sentMail($emailAdd, $subject, $content){
        //Sent mail login info
        Yii::import('application.extensions.phpmailer.JPhpMailer');
        $mail = new SmtpMailer();
        $mail->IsSMTP();
        $mail->SetFrom(SystemConfig::MAIL_ACCOUNT, SystemConfig::MAIL_NAME);

        $mail->Subject = $subject;
        $mail->MsgHTML($content);
        if(is_array($emailAdd)){
            foreach($emailAdd as $add){
                $mail->AddBCC($add);
            }
        }else{
            $mail->AddAddress($emailAdd);
        }

        if ($mail->Send()) {
            return true;
        } else {
           return false;
        }
    }

    /**
     * draw images by data
     *
     * @param array $dataArr data point
     * @param int $year year draw
     * @param string $drawText text label graph
     * @param bool $oneMonth one month or three month
     * @param int $w width image
     * @param int $h height image
     * @return bool|string url image | false
     */
    public static function drawGrapLineChart($dataArr=array(), $year, $drawText='', $oneMonth=true, $w=800, $h=400 ) {
        // validate year
        if((int)$year==0)
            return false;

        // import library
        $path = Yii::import('ext.pchart.*');
        define('PCHART_PATH',$path);
        require_once(PCHART_PATH.'/class/pData.class.php');
        require_once(PCHART_PATH.'/class/pDraw.class.php');
        require_once(PCHART_PATH.'/class/pImage.class.php');
        require_once(PCHART_PATH.'/class/pStock.class.php');

        /* Create and populate the pData object */
        $MyData = new pData();

        // add value(array) and SerieName
        /*
        $MyData->addPoints(array(-4,VOID,VOID,12,8,3),"Probe 1");
        $MyData->addPoints(array(3,12,15,8,5,-5),"Probe 2");
        $MyData->addPoints(array(2,7,5,18,19,22),"Probe 3");
        */
        if($dataArr){
            foreach($dataArr as $value){
                $MyData->addPoints($value['data'], $value['label']);
            }
        }else
            return false;

        // add style line
//        $MyData->setSerieTicks("Probe 2",4);
//        $MyData->setSerieWeight("Probe 3",2);
//        $MyData->setAxisName(0,"Temperatures");

        if($oneMonth){
            $filename = 'onemonth';
            $MyData->addPoints(array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),"Labels");

        }else{
            $filename = 'threemonth';
            $MyData->addPoints(array("Mar","Jun","Sep","Dec"),"Labels");
        }

        $MyData->setSerieDescription("Labels","Months");
        $MyData->setAbscissa("Labels");

        /* Create the pChart object */
        $myPicture = new pImage($w, $h, $MyData);

        /* Turn of Antialiasing */
        $myPicture->Antialias = FALSE;

        /* Add a border to the picture */
        $myPicture->drawRectangle(0,0,$w-1,$h-1,array("R"=>0,"G"=>0,"B"=>0));

        /* Write the chart title */
        $myPicture->setFontProperties(array("FontName"=>PCHART_PATH."/fonts/Forgotte.ttf","FontSize"=>11));

        if($drawText)
            $myPicture->drawText(150,35,$drawText,array("FontSize"=>20,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));

        /* Set the default font */
        $myPicture->setFontProperties(array("FontName"=>PCHART_PATH."/fonts/pf_arma_five.ttf","FontSize"=>6));

        /* Define the chart area */
        $myPicture->setGraphArea(60,40,$w-60,$h-40);

        /* Draw the scale */
        $scaleSettings = array("XMargin"=>10,"YMargin"=>10,"Floating"=>TRUE,"GridR"=>200,"GridG"=>200,"GridB"=>200,"DrawSubTicks"=>TRUE,"CycleBackground"=>TRUE);
        $myPicture->drawScale($scaleSettings);

        /* Turn on Antialiasing */
        $myPicture->Antialias = TRUE;

        /* Draw the line chart */
        $myPicture->drawLineChart();
        $myPicture->drawPlotChart(array("DisplayValues"=>TRUE,"PlotBorder"=>TRUE,"BorderSize"=>2,"Surrounding"=>-60,"BorderAlpha"=>80));

        /* Write the chart legend */
        $myPicture->drawLegend(540,20,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL));

//        $year = '2011';
        $dirByYear = 'images' . DIRECTORY_SEPARATOR . $year;
        $targetDirByYear = _ROOT_DIR_ . DIRECTORY_SEPARATOR . $dirByYear;
        if (!is_dir($targetDirByYear)) {
            mkdir($targetDirByYear, 0777, true);
        }

        $myPicture->render($dirByYear . DIRECTORY_SEPARATOR . $filename . ".png");

        $fileExist = $targetDirByYear . DIRECTORY_SEPARATOR . $filename . ".png";
        if (is_file($fileExist))
            return Yii::app()->getBaseUrl() . '/' . 'images' . '/' . $year . '/' . $filename . ".png";
        else
            return false;

    }

    public static function drawGrapBarChart($dataArr=array(), $year, $drawText='', $oneMonth=true, $w=800, $h=400 ) {
        // validate year
        if((int)$year==0)
            return false;

        // import library
        $path = Yii::import('ext.pchart.*');

        require_once($path.'/class/pData.class.php');
        require_once($path.'/class/pDraw.class.php');
        require_once($path.'/class/pImage.class.php');
        require_once($path.'/class/pStock.class.php');

        /* Create and populate the pData object */
        $MyData = new pData();

        // add value(array) and SerieName
        /*
        $MyData->addPoints(array(-4,VOID,VOID,12,8,3),"Probe 1");
        $MyData->addPoints(array(3,12,15,8,5,-5),"Probe 2");
        $MyData->addPoints(array(2,7,5,18,19,22),"Probe 3");
        */
        if($dataArr){
            foreach($dataArr as $value){
                $MyData->addPoints($value['data'], $value['label']);
            }
        }else
            return false;

        // add style line
//        $MyData->setSerieTicks("Probe 2",4);
//        $MyData->setSerieWeight("Probe 3",2);
//        $MyData->setAxisName(0,"Temperatures");

        if($oneMonth){
            $filename = 'onemonth-bar';
            $MyData->addPoints(array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),"Labels");

        }else{
            $filename = 'threemonth-bar';
            $MyData->addPoints(array("Mar","Jun","Sep","Dec"),"Labels");
        }

        $MyData->setSerieDescription("Labels","Months");
        $MyData->setAbscissa("Labels");

        /* Create the pChart object */
        $myPicture = new pImage($w, $h, $MyData);

        /* Turn of Antialiasing */
        $myPicture->Antialias = FALSE;

        /* Add a border to the picture */
        $myPicture->drawRectangle(0,0,$w-1,$h-1,array("R"=>0,"G"=>0,"B"=>0));

        /* Write the chart title */
        $myPicture->setFontProperties(array("FontName"=>$path."/fonts/Forgotte.ttf","FontSize"=>11));

        if($drawText)
            $myPicture->drawText(150,35,$drawText,array("FontSize"=>20,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));

        /* Set the default font */
        $myPicture->setFontProperties(array("FontName"=>$path."/fonts/pf_arma_five.ttf","FontSize"=>6));

        /* Define the chart area */
        $myPicture->setGraphArea(60,40,$w-60,$h-40);

        /* Draw the scale */
        $scaleSettings = array("GridR"=>200,"GridG"=>200,"GridB"=>200,"DrawSubTicks"=>TRUE,"CycleBackground"=>TRUE);
        $myPicture->drawScale($scaleSettings);

        /* Turn on Antialiasing */
//        $myPicture->Antialias = TRUE;

        /* Draw the line chart */
//        $myPicture->drawLineChart();
//        $myPicture->drawPlotChart(array("DisplayValues"=>TRUE,"PlotBorder"=>TRUE,"BorderSize"=>2,"Surrounding"=>-60,"BorderAlpha"=>80));

        /* Write the chart legend */
        $myPicture->drawLegend(540,20,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL));

        /* Turn on shadow computing */
        $myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));

        /* Draw the chart */
        $myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));
        $settings = array("Gradient"=>TRUE,"GradientMode"=>GRADIENT_EFFECT_CAN,"DisplayPos"=>LABEL_POS_INSIDE,"DisplayValues"=>TRUE,"DisplayR"=>255,"DisplayG"=>255,"DisplayB"=>255,"DisplayShadow"=>TRUE,"Surrounding"=>10);
        $myPicture->drawBarChart();

//        $year = '2011';
        $dirByYear = 'images' . DIRECTORY_SEPARATOR . $year;
        $targetDirByYear = _ROOT_DIR_ . DIRECTORY_SEPARATOR . $dirByYear;
        if (!is_dir($targetDirByYear)) {
            mkdir($targetDirByYear, 0777, true);
        }

        $myPicture->render($dirByYear . DIRECTORY_SEPARATOR . $filename . ".png");

        $fileExist = $targetDirByYear . DIRECTORY_SEPARATOR . $filename . ".png";
        if (is_file($fileExist))
            return Yii::app()->getBaseUrl() . '/' . 'images' . '/' . $year . '/' . $filename . ".png";
        else
            return false;

    }

    /**
     * convert csv to array
     *
     * @param $filePath path file csv
     * @param array $arrKeyMap convert key
     * @return array|bool
     */

    public static function csv2arr($filePath, $arrKeyMap = array()){
        if (($handle = fopen($filePath, "r")) === FALSE || !is_file($filePath))
            return false;
        $i = 0;
        $result = array();
        $arrkeyNew = array();
        while (($rows = fgetcsv($handle)) !== FALSE) {
            if($i==0){
                $arrkeyNew = self::_mapKeyCSV($rows, $arrKeyMap);
            }else{
                $result[] = array_combine($arrkeyNew, $rows);
            }
            $i++;
        }
        fclose($handle);
        if($result)
            return $result;
        else
            return false;

    }

    /**
     * map key of csv
     *
     * @param $header array
     * @param $arraySrc array convert
     * @return array
     */
    public static function _mapKeyCSV($header, $arraySrc) {
        $headerName = array();
        foreach ((array)$header as $title) {
        	$title = mb_convert_encoding($title, "UTF-8", "SJIS");
            $headerName[] = $arraySrc[trim($title)];
        }
        return $headerName;
    }
}